import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { Canvas, Path, Skia } from '@shopify/react-native-skia';
import { GestureDetector, Gesture } from 'react-native-gesture-handler';
import { runOnJS, useSharedValue, withTiming } from 'react-native-reanimated';

const NORMAL_STROKE = 10;
const SELECTED_STROKE = 12;
const ANIMATION_DURATION = 300; // 动画持续时间 (ms)
const MAX_SEGMENTS = 5; // 最大支持的 segment 数量
const COLORS = ['#60efff', '#00ff87', '#ff5858', '#f89b29', '#f492f0']; // Distinct colors

interface Segment {
  title: string;
  percent: number;
}

interface Props {
  data: Segment[];
  gapDegrees: number; // 圆弧间距（度）
  size: number; // Canvas 宽高
  padding?: number; // 可选 padding
}

const SegmentedRing: React.FC<Props> = ({ data, gapDegrees, size, padding = 20 }) => {
  const [selected, setSelected] = useState<number>(-1);

  // 验证输入
  if (typeof size !== 'number' || size <= 0) {
    console.warn('SegmentedRing: Size must be a positive number', { size });
    return <View style={styles.container}><Text>Size 必须是正数</Text></View>;
  }
  if (!Array.isArray(data) || data.length === 0) {
    console.warn('SegmentedRing: Invalid or empty data', { data });
    return <View style={styles.container}><Text>无效或空的数据</Text></View>;
  }
  if (data.length > MAX_SEGMENTS) {
    console.warn('SegmentedRing: Too many segments', { length: data.length, max: MAX_SEGMENTS });
    return <View style={styles.container}><Text>数据段数超过最大限制 {MAX_SEGMENTS}</Text></View>;
  }

  const CX = size / 2;
  const CY = size / 2;
  const RADIUS = size / 2 - padding;
  if (RADIUS <= 0) {
    console.warn('SegmentedRing: Radius is invalid', { size, padding, RADIUS });
    return <View style={styles.container}><Text>半径无效（检查 size 和 padding）</Text></View>;
  }

  const totalPercent = data.reduce((sum, item) => sum + (item.percent || 0), 0);
  if (totalPercent <= 0) {
    console.warn('SegmentedRing: Invalid total percent', { totalPercent });
    return <View style={styles.container}><Text>总百分比无效（percent 必须为正）</Text></View>;
  }

  // 计算最大 percent 的 index
  let maxIndex = -1;
  let maxPercent = -1;
  data.forEach((item, i) => {
    if (item.percent > maxPercent) {
      maxPercent = item.percent;
      maxIndex = i;
    }
  });

  // 初始化固定大小的 strokeWidths
  const strokeWidths = Array.from({ length: MAX_SEGMENTS }, () => useSharedValue(NORMAL_STROKE));

  // 初始化 selected 为最大 percent 的 index
  useEffect(() => {
    if (maxIndex !== -1) {
      setSelected(maxIndex);
    }
  }, [maxIndex]);

  // 当 selected 或 data 变化时，动画更新 strokeWidth
  useEffect(() => {
    strokeWidths.forEach((sw, i) => {
      const target = i < data.length && i === selected ? SELECTED_STROKE : NORMAL_STROKE;
      sw.value = withTiming(target, { duration: ANIMATION_DURATION });
    });
  }, [selected, data, strokeWidths]);

  // 限制 gapDegrees
  const maxGapDegrees = 360 / data.length;
  const effectiveGapDegrees = Math.min(gapDegrees, maxGapDegrees * 0.5);

  const gesture = Gesture.Tap().onStart((e) => {
    'worklet';
    const dx = e.x - CX;
    const dy = e.y - CY;
    const dist = Math.sqrt(dx * dx + dy * dy);

    // 检查点击是否在圆环范围内
    const inner = RADIUS - SELECTED_STROKE / 2;
    const outer = RADIUS + SELECTED_STROKE / 2;
    if (dist < inner || dist > outer) {
      return; // 忽略空白处点击
    }

    // 计算点击角度（0 为 3 点钟方向，顺时针增加）
    let angle = Math.atan2(dy, dx) * (180 / Math.PI);
    if (angle < 0) angle += 360;

    let start = 0;
    for (let i = 0; i < data.length; i++) {
      const sweep = (data[i].percent / totalPercent) * (360 - data.length * effectiveGapDegrees);
      const end = start + sweep;
      if (angle >= start && angle < end) {
        runOnJS(setSelected)(i);
        return;
      }
      start = end + effectiveGapDegrees;
    }
  });

  let startAngle = 0;
  const arcs = data.map((item, i) => {
    const sweep = (item.percent / totalPercent) * (360 - data.length * effectiveGapDegrees);
    if (sweep <= 0) {
      console.warn('SegmentedRing: Invalid sweep angle for segment', { index: i, sweep });
      return null;
    }
    const path = Skia.Path.Make();
    const oval = {
      x: CX - RADIUS,
      y: CY - RADIUS,
      width: RADIUS * 2,
      height: RADIUS * 2,
    };
    path.addArc(oval, startAngle, sweep);

    const color = COLORS[i % COLORS.length];

    startAngle += sweep + effectiveGapDegrees;

    return (
      <Path
        key={i}
        path={path}
        style="stroke"
        strokeWidth={strokeWidths[i]}
        color={color}
        strokeCap="round"
        strokeJoin="round"
      />
    );
  }).filter((arc) => arc !== null);

  const title = selected >= 0 && data[selected] ? data[selected].title : (maxIndex >= 0 && data[maxIndex] ? data[maxIndex].title : '');

  console.log('SegmentedRing: Rendering', { arcsLength: arcs.length, selected, title, size, padding, maxIndex });

  return (
    <View style={styles.container}>
      <GestureDetector gesture={gesture}>
        <View style={{ width: size, height: size }}>
          <Canvas style={{ width: size, height: size }}>
            {arcs}
          </Canvas>
          <Text style={[styles.title, { top: CY - 10 }]}>{title}</Text>
          {arcs.length === 0 && <Text style={styles.error}>无法渲染圆弧（检查数据 percent）</Text>}
        </View>
      </GestureDetector>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    position: 'absolute',
    left: 0,
    right: 0,
    textAlign: 'center',
    fontSize: 20,
    color: 'black',
  },
  error: {
    position: 'absolute',
    top: '50%',
    left: 0,
    right: 0,
    textAlign: 'center',
    color: 'red',
  },
});

export default SegmentedRing;